package cn.hallele.leinsteining.ms.support.starter.components.flow.executor;

import cn.hallele.leinsteining.mc.infrastructure.metadata.exceptions.children.LiteFlowException;
import cn.hutool.extra.spring.SpringUtil;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * Flow执行器
 *
 * @author anle5
 * @since 2024/8/4 21:34
 */
@Slf4j
public class FlowExec {
    private static final FlowExecutor FLOW_EXEC = SpringUtil.getBean(FlowExecutor.class);

    public static LiteflowResponse execute2Resp(String chainId, Object param, Object... contextBeanArray) {
        return getResponse(FLOW_EXEC.execute2Resp(chainId, param, contextBeanArray));
    }

    public static LiteflowResponse execute2Resp(String chainId, Object param, Class<?>... contextBeanClazzArray) {
        return getResponse(FLOW_EXEC.execute2Resp(chainId, param, contextBeanClazzArray));
    }

    public static LiteflowResponse execute2Resp(String chainId, Object param) {
        return getResponse(FLOW_EXEC.execute2Resp(chainId, param));
    }

    public static LiteflowResponse execute2Resp(String chainId) {
        return getResponse(FLOW_EXEC.execute2Resp(chainId));
    }

    private static LiteflowResponse getResponse(LiteflowResponse liteflowResponse) {
        if (liteflowResponse.isSuccess()) {
            return liteflowResponse;
        }

        log.error("Chain [{}] exec fail", liteflowResponse.getChainId());
        throw new LiteFlowException("Chain [" + liteflowResponse.getChainId() + "] exec fail");
    }
}